/**
 * @description 文件-服务
 * @since 2019-11-12
 * @author Rid King
*/

const ox = require('@daelui/oxjs')
const Model = require('./model.js')
const fs = require('fs')

class Service extends ox.Service {
  /**
   * @function 构造方法
  */
  constructor (args) {
    super(args)
    // 模型
    this.$model = new Model(args)
  }

  /**
   * @function 删除所有数据
   * @param {Object} action 操作集合
   * @demo
   * {
   *  req: {Request}
   *  res: {Response}
   *  data: {Object}
   * }
   * @return {Boolean/Error}
  */
  async deleteAll (action) {
    let result = true
    let res = await this.$model.where(action).find()
    result = await this.$model.delete()
    // 同步删除文件
    if (res.data) {
      this.deleteFile(res.data)
    }

    return result
  }

  /**
   * @function 删除文件
  */
  async deleteFile (list) {
    list = Array.isArray(list) ? list : []
    list.forEach(item => {
      if(fs.existsSync(item.path) && fs.statSync(item.path).isFile()) {
        fs.unlinkSync(item.path)
      }
    })
  }
}

module.exports = Service